package com.lm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lm.mapper.HealthInfoMapper;
import com.lm.mapper.ResidentMapper;
import com.lm.mapper.ServeMapper;
import com.lm.mapper.TagMapper;
import com.lm.pojo.*;
import com.lm.service.ResidentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashMap;
import java.util.List;

/**
 * @author LM
 * @version 1.0
 * @description: TODO
 * @date 2025/9/20 20:39
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ResidentServiceImpl implements ResidentService {



    @Autowired
    private ResidentMapper residentMapper;

    @Autowired
    private HealthInfoMapper healthInfoMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ServeMapper serveMapper;

    @Override
    public List<ResidentChatList> findResident(Integer residentId) {
        return residentMapper.selectResidentList();
    }

    @Override
    public IPage<Resident> findResidentList(SearchResident searchResident) {
        IPage<Resident> page = new Page<>(searchResident.getPageNo(), searchResident.getPageSize());
        IPage<Resident> pageInfo = residentMapper.findResidentList(page, searchResident.getResidentName(), searchResident.getResidentPhone());
        return pageInfo;
    }

    @Override
    public void addHalfResident(Resident resident) {
        resident.setResidentNumber(getResidentNumber(residentMapper.getResidentNumber()));
        residentMapper.addHalfResident(resident);
        setTagAndFamily(resident);

    }

    @Override
    public void addResident(ResidentAndHealth residentAndHealth) {
        Resident resident = residentAndHealth.getResident();
        HealthInfo healthInfo = residentAndHealth.getHealthInfo();
        resident.setResidentNumber(getResidentNumber(residentMapper.getResidentNumber()));
        residentMapper.insert(resident);
        setTagAndFamily(resident);
        healthInfo.setResidentId(resident.getResidentId());
        healthInfoMapper.insert(healthInfo);
    }

    @Override
    public List<Resident> findResidentName(String name) {
        QueryWrapper<Resident> query = new QueryWrapper<>();
        query.like("resident_name", name);
        return residentMapper.selectList(query);
    }

    @Override
    public List<Tag> findTags() {
        return tagMapper.selectList(null);
    }

    @Override
    public void changeStatus(Integer residentId, Integer status) {
        QueryWrapper<Resident> query = new QueryWrapper<>();
        query.eq("resident_id", residentId);
        Resident resident = new Resident();
        resident.setResidentId(residentId);
        resident.setResidentStatus(status);
        residentMapper.updateById(resident);

    }

    @Override
    public ResidentAndHealth findResidentById(Integer residentId) {
        QueryWrapper<Resident> query = new QueryWrapper<>();
        query.eq("resident_id", residentId);
        Resident resident = residentMapper.selectOne(query);
        QueryWrapper<HealthInfo> query1 = new QueryWrapper<>();
        query1.eq("resident_id", residentId);
        HealthInfo healthInfo = healthInfoMapper.selectOne(query1);
        List<String> tagName = residentMapper.findTagsName(residentId);
        List<Integer> tagId = residentMapper.findTagId(residentId);
        resident.setResidentTags(tagId);
        resident.setTagsName(tagName);
        ResidentAndHealth result = new ResidentAndHealth();
        result.setResident(resident);
        result.setHealthInfo(healthInfo);
        return result;
    }

    @Override
    public void saveChange(ResidentAndHealth residentAndHealth) {
        //删除旧标签以及旧家庭成员关联
        residentMapper.deleteResidentTag(residentAndHealth.getResident().getResidentId());
        residentMapper.deleteResidentAndFamily(residentAndHealth.getResident().getResidentId());
        Resident resident = residentAndHealth.getResident();
        //添加新标签以及家庭成员关联
        if (resident.getResidentTags() != null) {
            for (Integer tagId : resident.getResidentTags()) {
                residentMapper.insertTags(resident.getResidentId(), tagId);
            }
        }
        if (resident.getFamilyMember() != null) {
            for (HashMap<String, Object> map : resident.getFamilyMember()) {
                residentMapper.insertFamilyMember(resident.getResidentId(), (Integer) map.get("residentId"), (String) map.get("familyMemberRelationship"));
            }
        }

        //更新居民信息以及健康信息
        residentMapper.updateById(residentAndHealth.getResident());

        //更新健康信息，首先判断是否更改条件
        HealthInfo healthInfo = residentAndHealth.getHealthInfo();
        if (healthInfo.getResidentHealthAllergies() == 2) {
            healthInfo.setResidentHealthAllergiesDetails(null);
        }
        if (healthInfo.getResidentHealthPastDiseases() == 2) {
            healthInfo.setResidentHealthPastDiseasesDetails(null);
        }
        if (healthInfo.getResidentHealthFamilyHistory() == 2) {
            healthInfo.setResidentHealthFamilyHistoryDetails(null);
        }
        healthInfoMapper.update(healthInfo, new QueryWrapper<HealthInfo>().eq("resident_id", healthInfo.getResidentId()));
    }

    @Override
    public void deleteResident(Integer residentId) {
        //根据用户id删除所有与他相关的数据
        residentMapper.deleteResidentAndFamilyRelation(residentId);
        residentMapper.deleteMessage(residentId);
        residentMapper.deleteById(residentId);
        QueryWrapper<HealthInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("resident_health_id").eq("resident_id", residentId);
        HealthInfo healthInfo = healthInfoMapper.selectOne(queryWrapper);
        residentMapper.deleteResidentHealthInfo(residentId);
        if (healthInfo != null) {
            residentMapper.deleteServiceHealthInfo(healthInfo.getResidentHealthId());
        }

        residentMapper.deleteResidentTag(residentId);
        residentMapper.deleteServiceRecord(residentId);
        residentMapper.deleteSignRecord(residentId);
    }

    private void setTagAndFamily(Resident resident) {
        if (resident.getResidentTags() != null) {
            for (Integer tagId : resident.getResidentTags()) {
                residentMapper.insertTags(resident.getResidentId(), tagId);
            }
        }
        if (resident.getFamilyMember() != null) {
            for (HashMap<String, Object> map : resident.getFamilyMember()) {
                residentMapper.insertFamilyMember(resident.getResidentId(), (Integer) map.get("residentFamilyId"), (String) map.get("familyRelation"));
            }
        }

    }

    private String getResidentNumber(String num) {
        if (num != null && !num.isEmpty()) {
            try {
                int nextNum = Integer.parseInt(num) + 1;
                return String.valueOf(nextNum);
            } catch (NumberFormatException e) {
                // 处理数字格式异常，例如设置默认值或记录日志
                return "1"; // 默认从1开始
            }
        } else {
            return "1"; // 如果没有获取到编号，默认从1开始
        }
    }
}
